/**
 * Copyright (C), 2015-2021, XXX有限公司
 * FileName: StringTemplateUtils
 * Author:   zhuqifeng
 * Date:     2021/7/22 15:37
 * Description: 模板替换工具类
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.xlkj.ms.tools.core.utils;

import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 模板替换工具类
 * @author zhuqifeng
 * @date 2021/11/10 13:45
 * @package com.xlkj.ms.tools.core.utils
 */
public class StringTemplateUtils {

    public static final String DEF_REGEX = "\\{(.+?)\\}";

    public static String render(String template, Map<String, String> data) {
        return render(template, data, DEF_REGEX);
    }

    public static String render(String template, Map<String, String> data, String regex) {
        if (StringUtils.isBlank(template)) {
            return "";
        }
        if (StringUtils.isBlank(regex)) {
            return template;
        }
        if (data == null || data.size() == 0) {
            return template;
        }
        try {
            StringBuffer sb = new StringBuffer();
            Pattern pattern = Pattern.compile(regex);
            Matcher matcher = pattern.matcher(template);
            while (matcher.find()) {
                // 键名
                String name = matcher.group(1);
                // 键值
                String value = data.get(name);
                if (value == null) {
                    value = "";
                }
                matcher.appendReplacement(sb, value);
            }
            matcher.appendTail(sb);
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return template;

    }
}